package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApArticleSearchService;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleSearchServiceImpl implements ApArticleSearchService {


    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 按照标题 内容进行搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {

        if(dto==null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }


        //1、记录搜索的关键字到mongodb中
        ApUser apUser = ApThreadLocalUtil.get();  //不能saveKeyword方法里面获取，因为它是开的新线程
        if(apUser!=null){
            apUserSearchService.saveKeyword(dto.getSearchWords(),apUser.getId());
        }



        //2、到es进行关键词搜索
        try {
            //0。准备查询请求
            SearchRequest searchRequest = new SearchRequest("app_info_article");

            //1、指定查询条件
            //1.1用于将多个条件进行组合
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
            //1.2 multi_match查询
            MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(dto.getSearchWords(), "title", "content");
            //1.3 range查询
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
            //1.4 将multi_match查询和range查询通过boolQueryBuilder组合起来
            boolQueryBuilder.must(multiMatchQueryBuilder).filter(rangeQueryBuilder);


            searchRequest.source().query(boolQueryBuilder);   //设置查询条件
            searchRequest.source().size(dto.getPageSize());   //设置每页显示的条数
            searchRequest.source().sort("publishTime", SortOrder.DESC);   //指定排序
            searchRequest.source().highlighter(
                    new HighlightBuilder()
                            .field("title")   //指定标题高亮
                            .preTags("<em style='color:red;font-size:24px;font-weight:bold'>")
                            .postTags(("</em>"))
                            .requireFieldMatch(false)
            );  //指定高亮


            //3、发送查询请求
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();

            List<Map> list= new ArrayList<>();
            if(hits!=null && hits.length>0){
                for (SearchHit hit : hits) {
                    Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                    sourceAsMap.put("h_title",sourceAsMap.get("title"));

                    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                    if(highlightFields!=null){
                        HighlightField title = highlightFields.get("title");
                        if(title!=null){
                            String h_title = title.getFragments()[0].string();
                            sourceAsMap.put("h_title",h_title);
                        }
                    }

                    list.add(sourceAsMap);
                }
            }


            return ResponseResult.okResult(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
